<template>
  <div class="app-container">
    <!-- 搜索功能 -->
    <div>
      <span>姓名</span>
      <el-input
        v-model="nameParam"
        style="width: 200px; margin: 20px 10px 20px 20px"
        placeholder="请输入姓名"
      />
      <el-button type="primary" @click="fetchData">搜索</el-button>
    </div>
    <!-- 按钮 -->
    <div style="margin: 0px 0px 20px 0px">
      <el-row>
        <el-button
          type="primary"
          style="margin: 0px 20px"
          @click="addEmployee"
        >增加</el-button>
        <el-popconfirm
          title="是否删除这些数据？"
          @onConfirm="handleDelete()"
          @onCancel="handleCancel()"
        >
          <el-button
            slot="reference"
            type="danger"
            :disabled="!selectionText.length > 0"
            style="margin: 0px 10 0px 0px"
          >删除</el-button>
        </el-popconfirm>
      </el-row>
    </div>

    <!-- 用户表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="100" align="center" />

      <el-table-column align="center" label="序号" width="400">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="姓名" align="center" width="500">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="性别" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.sex | statusFilter">{{
            scope.row.sex === 'female' ? `女` : '男'
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="生日">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.birthday }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加 -->
    <el-dialog title="添加" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" value="male" />
            <el-option label="女" value="female" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-col :span="11">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogCancellation">取消</el-button>
          <el-button type="primary" @click="dialogCompletion">完成</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, addEmployee, deleteEmployee } from '@/api/employee'
export default {
  filters: {
    statusFilter(sex) {
      const statusMap = {
        male: 'gray',
        female: 'danger'
      }
      return statusMap[sex]
    }
  },
  data() {
    return {
      list: [],
      listLoading: true,
      // dialog 弹窗参数设置
      dialogVisible: false,

      // 查询
      nameParam: '',

      // dialog
      form: {
        name: '',
        sex: 'male',
        birthday: ''
      },
      // 选中内容
      selectionText: [],
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }]
      }
    }
  },

  created() {
    this.fetchData()
  },
  methods: {
    /**
     * 表格选择
     */
    handleSelectionChange(row) {
      this.selectionText = row
    },
    /**
     * 获取数据
     */
    fetchData() {
      this.listLoading = true
      getEmployeeList({ name: this.nameParam }).then((response) => {
        this.list = response.data.items
        this.listLoading = false
      })
    },

    /**
     * 点击添加打开dialog弹窗
     */
    addEmployee() {
      this.dialogVisible = true
    },

    /**
     * dialog 取消
     */
    dialogCancellation() {
      this.dialogVisible = false
      this.$refs.form.resetFields()
      this.form.birthday = ''
    },

    /**
     * 删除按钮
     */
    handleDelete() {
      deleteEmployee(this.selectionText).then((res) => {
        if (res.code === 20000) {
          this.$message.success('删除' + res.msg)
          this.fetchData()
        } else {
          this.$message.error('删除' + res.msg)
        }
      })
    },
    // Popconfirm  取消按钮
    handleCancel() {
      this.$message.warning('取消操作')
    },

    /**
     * 添加数据
     */
    dialogCompletion() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (typeof this.form.birthday === 'object') {
            this.form.birthday = this.dateFormat(
              'YYYY-mm-dd',
              this.form.birthday
            )
          }
          addEmployee(this.form).then((res) => {
            if (res.code === 20000) {
              this.$message.success('添加' + res.msg)
              this.fetchData()
              this.dialogVisible = false
              this.$refs.form.resetFields()
              this.form.birthday = ''
            } else {
              this.$message.error('添加' + res.msg)
            }
          })
        }
      })
    },

    /**
     * 日期格式化
     * @param {*} fmt 格式格式
     * @param {*} date 时间
     */
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    }
  }
}
</script>

<style scoped></style>
